import { Provide, Inject } from '@midwayjs/core';
import { DingtalkAuthService } from './dingtalk.auth.service'
import { OapiDingtalk } from '../utils/oapi.dingtalk'
import { JsonConfigModel } from '../entity/json_config.method'
@Provide()
export class AppConfigService {
  @Inject()
  DingtalkAuthService: DingtalkAuthService
  @Inject()
  OapiDingtalk: OapiDingtalk
  @Inject()
  JsonConfigModel: JsonConfigModel
  /**
   * 获取在职员工列表
   * @returns 
   */
  async getOnJobUserLists(): Promise<any> {
    //  获取apptoken
    const appToken = await this.DingtalkAuthService.getAppToken();
    if (!appToken || !appToken.success) return Promise.reject("获取应用token失败")

    const allUser = [];
    let _offset = 0;
    for (let i = 0; i < 100; i++) {
      //  获取在职员工列表 userid
      if (i == 0) {
        const res = await this.OapiDingtalk.queryOnJobUserLists(_offset, appToken.accessToken);
        if (res && res.success) {
          allUser.push(...res.data_list);
          _offset = res.next_cursor
        }
      } else {
        if (_offset) {
          const res = await this.OapiDingtalk.queryOnJobUserLists(_offset, appToken.accessToken);
          if (res && res.success) {
            allUser.push(...res.data_list);
            _offset = res.next_cursor
          }
        }
      }
    }
    console.log("########  总员工人数：", allUser.length)

    const allUserDetails = [];
    for (let k = 0; k < allUser.length; k++) {
      //  获取用户详细信息
      const userDetails = await this.OapiDingtalk.queryUserDetails(allUser[k], appToken.accessToken);
      if (userDetails && userDetails.success) {
        allUserDetails.push({
          userid: allUser[k],
          // mobile: userDetails.mobile,
          unionid: userDetails.unionid,
          name: userDetails.name,
          avatar: userDetails.avatar,
          email: userDetails.email || "",
        });
      } else {
        allUserDetails.push({
          userid: allUser[k],
          unionid: "",
          name: "",
          avatar: "",
          email: ""
        });
      }
    }

    //  在职员工列表编码
    const _code = "OnJobUser";
    const _name = "在职员工列表";
    //  查询当前配置数据是否存在
    const configInfo = await this.JsonConfigModel.getDataByCode(_code);
    if (configInfo && configInfo.length) {
      //  更新
      await this.JsonConfigModel.updateDateByCode({
        jsonCode: _code,
        jsonData: JSON.stringify(allUserDetails)
      })
    } else {
      //  新增
      await this.JsonConfigModel.insertDataInfo({
        jsonCode: _code,
        jsonName: _name,
        jsonData: JSON.stringify(allUserDetails)
      })
    }

    return true
  }

  /**
   * 根据code 获取json数据
   * @param {*} code 
   */
  async getDataByCode(code:any): Promise<any> {
    const _codes = code.split(",");
    const _resData = {}
    for (let i = 0; i < _codes.length; i++) {
      const configInfo = await this.JsonConfigModel.getDataByCode(_codes[i]);
      if (configInfo && configInfo.length) {
        _resData[_codes[i]] = configInfo[0].json_data ? JSON.parse(configInfo[0].json_data) : null;
      } else {
        _resData[_codes[i]] = null;
      }
    }
    return _resData
  }

  /**
   * json数据分页查询
   * @param {*} pageSize
   * @param {*} pageNum
   * @param {*} searchKey
   */
  async getJsonConfigList(params:any): Promise<any> {
    const { pageSize, pageNum, searchKey } = params;

    const total = await this.JsonConfigModel.getTotalNum(searchKey);
    const res = {
      total: total[0].num,
      lists: []
    }

    if (total[0].num) {
      const resList = await this.JsonConfigModel.getDataByPage(pageNum, pageSize, searchKey);
      res.lists = resList;
    }
    return res

  }

  /**
   * 新增json数据
   * @param {*} jsonCode 
   * @param {*} jsonName 
   * @param {*} jsonData 
   */
  async insertJsonConfigData(params:any): Promise<any> {
    const total = await this.JsonConfigModel.getCountByCode(params.jsonCode);
    if (total[0].num) return Promise.reject('当前编码code已存在，请重新输入')
    return await this.JsonConfigModel.insertDataInfo(params);
  }

  /**
   * 修改json数据
   * @param {*} id
   * @param {*} jsonData 
   */
  async updateJsonConfigData(params:any): Promise<any> {

    const res = await this.JsonConfigModel.updateDateById(params);
    return res

  }

  /**
   * 获取更新部门树
   */
  async getDeptTree(): Promise<any> {

    //  获取apptoken
    const appToken = await this.DingtalkAuthService.getAppToken();
    if (!appToken || !appToken.success) return Promise.reject("获取应用token失败")

    //  获取当前部门下的用户id
    const _deptTree = await this.getUserListsByDeptId(1, appToken.accessToken);

    //  部门用户列表树编码
    const _code = "DeptsUserTree";
    const _name = "部门用户列表树";
    //  查询当前配置数据是否存在
    const configInfo = await this.JsonConfigModel.getDataByCode(_code);
    if (configInfo && configInfo.length) {
      //  更新
      await this.JsonConfigModel.updateDateByCode({
        jsonCode: _code,
        jsonData: JSON.stringify(_deptTree)
      })
    } else {
      //  新增
      await this.JsonConfigModel.insertDataInfo({
        jsonCode: _code,
        jsonName: _name,
        jsonData: JSON.stringify(_deptTree)
      })
    }
    return true
  }

  /**
   * 根据部门id获取部门下所有用户信息
   * @param {*} deptId 
   * @param {*} appToken 
   * @returns 
   */
  async getUserListsByDeptId(deptId:any, appToken:any): Promise<any> {
    try {
      const resData: any = {};

      // let { user_lists, dept_lists } = await this.getDeptDetails(deptId, appToken);
      const result = await this.getDeptDetails(deptId, appToken);
      resData.user_lists = result.user_lists;
      resData.dept_id = deptId;
      resData.dept_lists = await this.pollingDeptData(result.dept_lists, appToken);
      return resData;
    } catch (error) {
      console.log("##########  getUserListsByDeptId-error:", error)
      return {};
    }
  }

  /**
   * 轮询调用接口获取部门数据
   * @param {*} deptLists 
   * @param {*} appToken 
   * @returns 
   */
  async pollingDeptData(deptLists:any, appToken:any): Promise<any> {
    try {
      for (let i = 0; i < deptLists.length; i++) {
        const deptId = deptLists[i].dept_id;
        const { user_lists, dept_lists } = await this.getDeptDetails(deptId, appToken);
        deptLists[i].user_lists = user_lists;
        if (dept_lists && dept_lists.length) {
          deptLists[i].dept_lists = await this.pollingDeptData(dept_lists, appToken)
        } else {
          deptLists[i].dept_lists = [];
        }
      }
      return deptLists;
    } catch (error) {
      console.log("######  pollingDeptData:", error);
      return [];
    }
  }

  /**
   * 获取部门下的子部门以及当前部门的用户数据
   * @param {*} deptId 
   * @param {*} appToken 
   */
  async getDeptDetails(deptId:number, appToken:any): Promise<any> {
    try {
      const user_lists = [];
      //  获取部门用户信息
      const userLists = await this.OapiDingtalk.queryUserListsimple(deptId, appToken);
      if (userLists.success && userLists.list && userLists.list.length) {
        userLists.list.forEach(item => {
          user_lists.push(item);
        })
      }
      //  获取下级部门信息
      let dept_lists = [];
      const childDept = await this.OapiDingtalk.queryDepartmentList(deptId, appToken);
      if (childDept.success) {
        const _deptRes = Object.values(childDept);
        _deptRes.pop();
        let _deptRes_item: any = '';
        for (let i = 0; i < _deptRes.length; i++) {
          _deptRes_item = _deptRes[i]
          const el: any = _deptRes_item;
          if (el.ext) {
            _deptRes_item.ext = JSON.parse(el.ext);
          }

        }
        dept_lists = _deptRes;
      }
      return {
        user_lists,
        dept_lists
      }
    } catch (error) {
      return {
        user_lists: [],
        dept_lists: []
      }
    }
  }

}